#include<stdio.h>
#include<time.h>
#include<unistd.h>
#include<sys/time.h>

#include<gpiox.h>

#define DEBUG 0

static int high_distance = 0.0;

int us100(const int init_group,
        const int init_pin_num,
        const int back_group,
        const int back_pin_num,
        int *retval) {
    /* ultrasonic distance-detecter init-signal
     * uart communicate mode */
    gpio_write(init_group, init_pin_num, 1);
    usleep(15);
    gpio_write(init_group, init_pin_num, 0);

    /* wait for the echo back signal */
    int pin_val;
    struct timeval echo_start_time,
                   echo_stop_time;

    /* wait it for the echo-signal start */
    while(1) {
        gpio_read(back_group, back_pin_num, &pin_val);
        if(pin_val) {
            gettimeofday(&echo_start_time, NULL);
            break;
        }
    }


    /* wait it for the echo-signal stop */
    while(1) {
        gpio_read(back_group, back_pin_num, &pin_val);
        if(!pin_val) {
            gettimeofday(&echo_stop_time, NULL);
            break;
        }
    }
    double high_vol_time =
        (echo_stop_time.tv_sec - echo_start_time.tv_sec) * 1.0 +
        ((echo_stop_time.tv_usec - echo_start_time.tv_usec) * 1.0 )/ (1000 * 1000);

    /* calculated the distance */
    high_distance = high_vol_time * (340 / 2.0) * 100;
    /* the velocity of sound is 340m/s
     * 100cm == 1m*/

    if(retval)
        *retval = high_distance;

#if DEBUG
    printf("start %lds %ldus\n", echo_start_time.tv_sec, echo_start_time.tv_usec);
    printf("stop %lds %ldus\n", echo_stop_time.tv_sec, echo_stop_time.tv_usec);
    printf("hig_vol_time is %lf\n", high_vol_time);
#endif

    return  0;
}

double get_distance(void) {
    return high_distance;
}
